#include "Peer.h"

static size_t my_write_func(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
  return fwrite(ptr, size, nmemb, stream);
}

static size_t my_read_func(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
  return fread(ptr, size, nmemb, stream);
}

static int progress_func(void* ptr, double TotalToDownload, double NowDownloaded, double TotalToUpload, double NowUploaded)
{
    progress = NowDownloaded/TotalToDownload;
    return 0;
}

Peer::Peer(std::string url, std::string name){
        _name = (char*)name.c_str();
        _url = (char*)url.c_str();
}

void Peer::runsingle(){
  CURL *curl;
  CURLcode res;
  FILE *outfile;

  curl = curl_easy_init();
  if(curl)
  {
    outfile = fopen(_name, "w");

    curl_easy_setopt(curl, CURLOPT_URL, _url);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, outfile);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_write_func);
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, my_read_func);
    res = curl_easy_perform(curl);
    if(CURLE_OK == res) {
        //res = curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &totalbyte);
        //res = curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &totaltime);
    }

    fclose(outfile);
    curl_easy_cleanup(curl);
  }
}

void Peer::run(){
  Peer *pe = this;
  Peer::CreateTask(pe);
}

void Peer::runprogress(){
  CURL *curl;
  CURLcode res;
  FILE *outfile;

  curl = curl_easy_init();
  if(curl)
  {
    outfile = fopen(_name, "w");

    curl_easy_setopt(curl, CURLOPT_URL, _url);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, outfile);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_write_func);
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, my_read_func);
    curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false);
    curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_func);

    res = curl_easy_perform(curl);
    if(CURLE_OK == res) {
        res = curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &totalbyte);
        res = curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &totaltime);
    }

    fclose(outfile);
    curl_easy_cleanup(curl);
  }
}
